package minioService

import (
	"backend/config"
	"context"
	"fmt"
	"github.com/google/uuid"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"github.com/minio/minio-go/v7/pkg/policy"
	"io"
	"net/http"
)

var minioClient *minio.Client

//var minioClient, _ = minio.New(Endpoint, &minio.Options{
//	Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
//	Secure: false,
//})

func Init() {
	var err error
	minioClient, err = minio.New(config.Config.Minio.Endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4("mataoxun", "mtx990812", ""),
		Secure: false,
	})
	if err != nil {
		fmt.Println(err.Error())
	}

}

const (
	//Endpoint = "82.156.206.110:4102"
	Endpoint        = "zjx_minio:9000"
	accessKeyID     = "mataoxun"
	secretAccessKey = "mtx990812"
	//accessKeyID     = "minioadmin"
	//secretAccessKey = "minioadmin"
	useSSL   = false
	location = "us-east-1"
)

func MakeBucket(bucketName string) error {
	err := minioClient.MakeBucket(context.Background(), bucketName, minio.MakeBucketOptions{Region: location})
	return err
}

func OpenPolicy(bucketName string) {
	err := minioClient.SetBucketPolicy(context.Background(), bucketName, policy.BucketPolicyReadWrite)
	if err != nil {
		fmt.Println(err.Error())
	}
}

func UploadFile(bucketName string, fileName string, folderPath string, file io.Reader) (error, minio.UploadInfo) {
	u := uuid.New()
	s := u.String()
	object, err := minioClient.PutObject(context.Background(), bucketName, folderPath+s+"_zjx_"+fileName, file, -1, minio.PutObjectOptions{})
	if err != nil {
		return err, object
	}
	return nil, object
}

func GetFile(fileName string, bucketName string) ([]byte, string) {
	object, err := minioClient.GetObject(context.Background(), bucketName, fileName, minio.GetObjectOptions{})
	if err != nil {
		return nil, ""
	}
	stat, err := object.Stat()
	byteList := make([]byte, stat.Size)
	_, err = object.Read(byteList)
	fmt.Println(stat.Size)
	if err != nil {
		fmt.Println(err)
	}

	return byteList, stat.ContentType
}

func GetFileContentType(buffer []byte) (string, error) {

	// Only the first 512 bytes are used to sniff the content type.

	// Use the net/http package's handy DectectContentType function. Always returns a valid
	// content-type by returning "application/octet-stream" if no others seemed to match.
	contentType := http.DetectContentType(buffer)

	return contentType, nil
}
